package com.aiti.lulian.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CustomerContactsDto;
import com.aiti.lulian.dto.crm.SupplyToCRMParamDto;
import com.aiti.lulian.entity.CustomerContacts;
import com.aiti.lulian.entity.CustomerContactsRelation;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CustomerContactsMapper;
import com.aiti.lulian.service.ICustomerContactsRelationService;
import com.aiti.lulian.service.ICustomerContactsService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.utils.DateFilterUtil;
import com.aiti.lulian.vo.CustomerContactsVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomerContactsServiceImpl extends BaseSerivceImpl<CustomerContactsMapper, CustomerContacts> implements ICustomerContactsService {

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;
    @Autowired
    private ICustomerContactsRelationService customerContactsRelationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message insertContact(CustomerContactsDto dto) {
        dto.setDirectorId(dto.getUserId());
        Message message = cloudShowManagerSubService.getUserInfo(dto.getDirectorId());
        if (message == null) {
            return Message.fail("获取用户信息失败！");
        }
        Object obj = message.getObj();
        if (obj == null) {
            return Message.fail("获取用户信息失败！");
        }
        if (message.getCode() == 1) {
            return Message.fail("查询用户信息错误");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map resultMap = mapper.convertValue(obj, Map.class);
        String deptId = (String)resultMap.get("deptId");
        String deptName = (String)resultMap.get("deptName");
        String directorName = (String)resultMap.get("realname");
        String enterpriseId = (String)resultMap.get("companyId");
        if(StringUtils.isEmpty(enterpriseId)){
            LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", dto.getDirectorId()));
            if(enterpriseUser != null){
                enterpriseId = enterpriseUser.getEnterpriseId();

            }else{
                return Message.fail("获取所选负责人企业信息失败！");
            }
        }
        dto.setEnterpriseId(enterpriseId);
        dto.setDeptId(deptId);
        dto.setDirectorName(directorName);
        dto.setDeptName(deptName);
        //查询是否重复：电话+联系人姓名
        int count = this.count(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, dto.getContactsName()).eq(CustomerContacts::getTelephone, dto.getTelephone()).eq(CustomerContacts::getEnterpriseId, enterpriseId));
        if(count > 0){
            return Message.fail("该电话以及联系人姓名对应的联系人已存在！");
        }
        CustomerContacts customerContacts = new CustomerContacts();
        BeanUtils.copyProperties(dto, customerContacts);
        this.save(customerContacts);
        //添加联系人关系
        List<String> customerIdList = dto.getCustomerIdList();
        List<CustomerContactsRelation> relationList  = new ArrayList<>();
        if(!CollectionUtils.isEmpty(customerIdList)){
            customerIdList.forEach(customerId -> {
                CustomerContactsRelation relation  = new CustomerContactsRelation();
                relation.setContactId(customerContacts.getBaseId());
                relation.setCustomerId(customerId);
                relationList.add(relation);
            }
            );
        }
        customerContactsRelationService.saveBatch(relationList);
        return Message.success("添加成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message updateContact(CustomerContactsDto dto) {
        CustomerContacts oldContact = this.getById(dto.getBaseId());
        if(oldContact == null){
            return Message.fail("联系人不存在！");
        }
        //查询是否重复：电话+联系人姓名
        int count = this.count(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, dto.getContactsName()).eq(CustomerContacts::getTelephone, dto.getTelephone()).eq(CustomerContacts::getEnterpriseId, oldContact.getEnterpriseId()).ne(CustomerContacts::getBaseId, dto.getBaseId()));
        if(count > 0){
            return Message.fail("该电话以及联系人姓名对应的联系人已存在！");
        }
        CustomerContacts customerContacts = new CustomerContacts();
        BeanUtils.copyProperties(dto, customerContacts);
        customerContacts.setUpdateBy(dto.getUserId());
        customerContacts.setBaseUpdateTime(new Date());
        this.updateById(customerContacts);
        customerContactsRelationService.remove(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getContactId, dto.getBaseId()));
        //添加联系人关系
        List<String> customerIdList = dto.getCustomerIdList();
        List<CustomerContactsRelation> relationList  = new ArrayList<>();
        if(!CollectionUtils.isEmpty(customerIdList)){
            customerIdList.forEach(customerId -> {
                        CustomerContactsRelation relation  = new CustomerContactsRelation();
                        relation.setContactId(customerContacts.getBaseId());
                        relation.setCustomerId(customerId);
                        relationList.add(relation);
                    }
            );
        }
        customerContactsRelationService.saveBatch(relationList);
        return Message.success("修改成功！");
    }

    @Override
    public Message contactPage(Page page, CustomerContactsDto dto) {
        String createUserId = dto.getUserId();
        String roleIds = dto.getRoleIds();
        if(StringUtils.isEmpty(roleIds)){
            Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(createUserId);
            if (userRoleMessage == null) {
                return Message.fail("获取角色信息失败！");
            }
            roleIds = (String)userRoleMessage.getObj();

            if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("查询用户失败");
            }

        }
        if(!StringUtils.isEmpty(roleIds)) {
            String[] split = roleIds.split(StrUtil.COMMA);
            boolean systemAdmin = Arrays.stream(split).filter(f -> "1".equals(f)).count() > 0;
            dto.setSystemAdmin(systemAdmin);
            dto.setUserId(createUserId);
            String dateFilterType = dto.getDateFilterType();
            Date beginDate = dto.getBeginDate();
            Date endDate = dto.getEndDate();
            if(beginDate != null){
                beginDate = DateUtil.beginOfDay(beginDate);
                dto.setBeginDate(beginDate);
            }
            if(endDate != null){
                endDate = DateUtil.endOfDay(endDate);
                dto.setEndDate(endDate);
            }
            if(!StringUtils.isEmpty(dateFilterType)){
                Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(dateFilterType);
                dto.setBeginDate(beginAndEnd.get("begin"));
                dto.setEndDate(beginAndEnd.get("end"));
            }
            if (!systemAdmin) {
                Message message = cloudShowManagerSubService.getUserInfo(createUserId);
                if (message == null) {
                    return Message.fail("获取用户信息失败！");
                }
                Object obj = message.getObj();
                if (obj == null) {
                    return Message.fail("获取用户信息失败！");
                }
                if (message.getCode() == 1) {
                    return Message.fail("查询用户信息错误");
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                String deptPermission = "";
                //获取当前用户的权限
                Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(createUserId);
                if (userAccessScopeMessage == null) {
                    throw new RuntimeException("获取用户权限失败");
                } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户权限失败");
                } else {
                    deptPermission = (String) userAccessScopeMessage.getObj();
                }
                String deptId = (String)resultMap.get("deptId");
                String enterpriseId = (String)resultMap.get("companyId");
                if(StringUtils.isEmpty(enterpriseId)){
                    LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", createUserId));
                    if(enterpriseUser != null){
                        enterpriseId = enterpriseUser.getEnterpriseId();

                    }else{
                        return Message.fail("获取所选负责人企业信息失败！");
                    }
                }
                dto.setEnterpriseId(enterpriseId);
                dto.setDeptPermission(deptPermission);
                dto.setDeptId(deptId);
                List<String> deptList = new ArrayList();
                if(!StringUtils.isEmpty(deptId)){
                    deptList.add(deptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            deptList.add(temp);
                        }
                    }
                }

                dto.setDeptList(deptList);
            }
        }else{
            PageResult rspData = new PageResult(new ArrayList(), new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
            return Message.success(rspData);
        }

        List<CustomerContactsVo> list = this.getBaseMapper().selectContactsList(page, dto);
        PageResult rspData = new PageResult(list, new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
        return Message.success(rspData);
    }

    @Override
    public Message detailInfo(String baseId) {
        CustomerContactsVo detailInfo = this.getBaseMapper().detailInfo(baseId);
        return Message.success(detailInfo);
    }

    @Override
    public Message updateListCustomerContact(CustomerContactsDto dto) {
        String field = dto.getField();
        String filedValue = dto.getFieldValue();
        List<String> idList = dto.getIdList();
        if(!StringUtils.isEmpty(field) && !StringUtils.isEmpty(filedValue)){
            UpdateWrapper<CustomerContacts> wrapper = new UpdateWrapper<>();
            field = StrUtil.toUnderlineCase(field);
            wrapper.set(field, filedValue).in("base_id", idList);
            this.update(wrapper);
        }else{
            return Message.fail("请重新编辑字段！");
        }

        return Message.success();
    }

    @Override
    public List<CustomerContacts> getList(String customerId) {
        List<CustomerContacts> customerContactList = this.baseMapper.getContactListByCustomerId(customerId);
        return customerContactList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message updateCustomerContactsBatch(CustomerContactsDto dto) {
        String userId = dto.getUserId();
        String enterpriseId = dto.getEnterpriseId();
        String customerId = dto.getCustomerId();
        List<CustomerContacts> customerContactsList = dto.getCustomerContactsList();
        //更新
        List<CustomerContacts> hasBaseIdContactsList = customerContactsList.stream().filter(i -> StrUtil.isNotBlank(i.getBaseId())).peek(i -> {
            i.setUpdateBy(userId);
            i.setBaseUpdateTime(new Date());
        }).collect(Collectors.toList());
        this.updateBatchById(hasBaseIdContactsList);
        //删除
        List<String> hasBaseIdContactsIdList = hasBaseIdContactsList.stream().map(CustomerContacts::getBaseId).collect(Collectors.toList());
        List<CustomerContacts> list = this.getList(customerId);
        List<String> existingContactsIdList = list.stream().map(CustomerContacts::getBaseId).collect(Collectors.toList());
        existingContactsIdList.removeAll(hasBaseIdContactsIdList);
        if (existingContactsIdList.size() > 0) {
            for (String contactsId : existingContactsIdList) {
                customerContactsRelationService.remove(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getContactId, contactsId).eq(CustomerContactsRelation::getCustomerId, customerId));
            }
        }
        //新增
        List<CustomerContacts> nullBaseIdContactsList = customerContactsList.stream().filter(i -> StrUtil.isBlank(i.getBaseId())).collect(Collectors.toList());
        for (CustomerContacts customerContacts : nullBaseIdContactsList) {
            CustomerContacts contacts = this.getOne(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, customerContacts.getContactsName()).eq(CustomerContacts::getTelephone, customerContacts.getTelephone()).eq(CustomerContacts::getEnterpriseId, enterpriseId));
            if (contacts != null) {
                String baseId = contacts.getBaseId();
                CustomerContactsRelation relation = customerContactsRelationService.getOne(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getCustomerId, customerId).eq(CustomerContactsRelation::getContactId, baseId));
                if (relation == null) {
//                customerContacts.setBaseId(baseId);
//                customerContacts.setUpdateBy(userId);
//                customerContacts.setBaseUpdateTime(new Date());
//                this.updateById(customerContacts);
                    CustomerContactsRelation contactsRelation = CustomerContactsRelation.builder().customerId(customerId).contactId(baseId).baseCreateTime(new Date()).build();
                    customerContactsRelationService.save(contactsRelation);
                }
            } else {
                customerContacts.setDeptId(dto.getDeptId());
                customerContacts.setDeptName(dto.getDeptName());
                customerContacts.setPosition(dto.getPosition());
                customerContacts.setDirectorId(dto.getDirectorId());
                customerContacts.setDirectorName(dto.getDirectorName());
                customerContacts.setEnterpriseId(dto.getEnterpriseId());
                customerContacts.setCreator(userId);
                customerContacts.setBaseCreateTime(new Date());
                this.save(customerContacts);
                CustomerContactsRelation customerContactsRelation = CustomerContactsRelation.builder().customerId(customerId).contactId(customerContacts.getBaseId()).baseCreateTime(new Date()).build();
                customerContactsRelationService.save(customerContactsRelation);
            }
        }
        return Message.success();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void createContactAndRelation(String ContactsName, String ContactsPhone, String customerId, String creator, String enterpriseId, SupplyToCRMParamDto supplyToCRMParamDto) {
        CustomerContacts contacts = CustomerContacts.builder().contactsName(ContactsName).directorName(supplyToCRMParamDto.getRealName()).directorId(creator).deptName(supplyToCRMParamDto.getDeptName()).deptId(supplyToCRMParamDto.getDeptId()).contactsPhone(ContactsPhone).enterpriseId(enterpriseId).creator(creator).baseCreateTime(new Date()).build();
        this.save(contacts);
        CustomerContactsRelation relation = CustomerContactsRelation.builder().customerId(customerId).contactId(contacts.getBaseId()).baseCreateTime(new Date()).build();
        customerContactsRelationService.save(relation);
    }
}